/***************************************************
 ** @Desc : This file for 根据商户订单号查询支付宝订单号
 ** @Time : 2018.12.26 15:25 
 ** @Author : Joker
 ** @File : trade_query
 ** @Last Modified by : Joker
 ** @Last Modified time: 2018.12.26 15:25
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"sub_account/models"
	"io/ioutil"
	"encoding/json"
	"strings"
	"sub_account/utils"
	"net/http"
	"net/url"
)

type TradeQuery struct{}

func (*TradeQuery) QueryAlipayTradeNo(out_trade_no, app_id, private_key string) (string, string) {
	//构造请求参数
	req_params := map[string]interface{}{
		"out_trade_no": out_trade_no,
	}

	//生成请求内容
	//请求内容(由请求参数拼接成的JSON串)
	content, _ := json.Marshal(req_params)
	bizContent := string(content)

	method := utils.QUERY_METHOD
	format := utils.DATA_FORMAT
	charset := utils.CHARSET
	sign_type := utils.SIGN_TYPE
	nowTime := global.GetNowTime()
	version := utils.VERSION
	//构造参与签名的公共请求参数
	resp_pub_params := map[string]string{
		"app_id":      app_id,
		"method":      method,
		"format":      format,
		"charset":     charset,
		"sign_type":   sign_type,
		"timestamp":   nowTime,
		"version":     version,
		"biz_content": bizContent,
	}

	//生成签名
	sign_string := encrypt.ToStringByMapRemoveSign(resp_pub_params)
	sign_RSA, err0 := encrypt.SHA256WithRSAToSign([]byte(sign_string), []byte(private_key))
	if err0 != nil {
		utils.LogError("QueryAlipayTradeNo failed to generate sign_RSA for: ", err0)
	}
	sign := encrypt.Base64Encode(sign_RSA) //签名

	//发送请求
	resp, err1 := http.PostForm(utils.REQUEST_URL, url.Values{
		"app_id":      {app_id},
		"method":      {method},
		"format":      {format},
		"charset":     {charset},
		"sign_type":   {sign_type},
		"timestamp":   {nowTime},
		"version":     {version},
		"biz_content": {bizContent},
		"sign":        {sign},
	})

	//请求出错
	if err1 != nil {
		utils.LogError("QueryAlipayTradeNo failed to submit form: ", err1)
	}
	defer resp.Body.Close()

	//接收返回值
	html, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		utils.LogError("QueryAlipayTradeNo failed to receive data: ", err2)
	}
	//编码格式转为UTF-8
	body, err3 := global.GbkToUtf8(html)
	if err3 != nil {
		utils.LogNotice("GBK failed to transfer utf-8 for: ", err3)
	}

	//do something,handle receive data
	publicParams := models.PublicQueryResponseParams{}
	json.Unmarshal([]byte(string(body)), &publicParams) //string to json

	verify_string := publicParams.AlipayTradeQueryResponse //返回的参数
	if strings.Compare("10000", verify_string.Code) == 0 &&
		strings.Compare(out_trade_no, verify_string.OutTradeNo) == 0 {
		return verify_string.TradeNo, verify_string.SubMsg
	} else {
		return "", verify_string.SubMsg
	}
}
